package com.groupfifteen.controller;

import com.groupfifteen.entity.SysLoginEntity;
import com.groupfifteen.entity.SysUserEntity;
import com.groupfifteen.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequiredArgsConstructor
public class SysUserLoginController {
    private final SysLoginService sysLoginService;
    @PostMapping("/loginuser")
    public ResponseEntity<String> login(@RequestBody SysLoginEntity sysLoginEntity, HttpServletResponse response) {
        Integer id = sysLoginEntity.getId();
        String password = sysLoginEntity.getPassword();
        //登录学生
        SysUserEntity user = sysLoginService.userLogin(id, password);
        if (user != null) {
            // 设置token和角色的Cookie
            String token = "your_token_generation_logic"; // 这里应该是生成token的逻辑
            String role = user.getIdNo(); // 假设SysUserEntity中有getRole()方法

            Cookie tokenCookie = new Cookie("rb_token", token);
            tokenCookie.setPath("/");
            tokenCookie.setHttpOnly(true);
            tokenCookie.setSecure(true); // 如果是HTTPS环境
            response.addCookie(tokenCookie);

            Cookie roleCookie = new Cookie("rb_role", role);
            roleCookie.setPath("/");
            roleCookie.setHttpOnly(true);
            roleCookie.setSecure(true); // 如果是HTTPS环境
            response.addCookie(roleCookie);

            return ResponseEntity.ok("登录成功");
        } else {
            return ResponseEntity.status(org.springframework.http.HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }
}
